package models

import (
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
	"lottery/libs/mymgo"
)

const (
	USER_COL_STR = "user"
)

type User struct {
	Id             int64  `json:"id" bson:"_id"`                                    // 客户Id
	UserName       string `json:"userName" bson:"userName"`                         // 昵称
	PhoneNumb      string `json:"phoneNumb,omitempty" bson:"phoneNumb"`             // 手机号码
	Code           string `json:"code,omitempty" bson:"-"`                          // 验证码
	InvitationCode string `json:"invitation,omitempty" bson:"invitation,omitempty"` // 邀请码
	Email          string `json:"email,omitempty" bson:"email"`                     // 邮件
	Password       string `json:"passWord,omitempty" bson:"passWord"`               // 密码
	Age            string `json:"age,omitempty" bson:"age"`                         // 年龄
	QQ             string `json:"qq,omitempty" bson:"qq"`                           // QQ
	Status         int    `json:"status,omitempty" bson:"status"`                   // 状态 1 停用 2 启用

	CreateTime int64 `json:"createTime,omitempty" bson:"createTime"` // 创建时间
	UpdateTime int64 `json:"updateTime,omitempty" bson:"updateTime"` // 更新时间
	DeleteTime int64 `json:"deleteTime,omitempty" bson:"deleteTime"` // 删除时间
	IsDeleted  bool  `json:"isDeleted,omitempty" bson:"isDeleted"`   // 是否删除
}

func GetAllUser() (users []*User, err error) {
	sess, err := mymgo.OpenBase()
	if err != nil {
		return
	}

	users = make([]*User, 0, 100)
	err = sess.All(USER_COL_STR, bson.M{"isDeleted": false}, &users)
	return
}

func FindUserInfo(userId int64) (user *User, err error) {
	sess, err := mymgo.OpenBase()
	if err != nil {
		return
	}

	user = &User{}
	err = sess.WithC(USER_COL_STR, func(col *mgo.Collection) error {
		return col.Find(bson.M{"_id": userId}).Select(bson.M{"userName": 1}).One(user)
	})
	return
}

func SaveUser(user *User) (err error) {
	sess, err := mymgo.OpenBase()
	if err != nil {
		return
	}

	user.Status = 2
	user.Id = int64(sess.AutoIncId(USER_COL_STR))
	return sess.Insert(USER_COL_STR, user)
}

func ExistsPhoneNumb(phoneNumb string) (exists bool) {

	sess, err := mymgo.OpenBase()
	if err != nil {
		return
	}

	return sess.Exist(USER_COL_STR, bson.M{"phoneNumb": phoneNumb})
}

func ExistsEmail(email string) (exists bool) {
	sess, err := mymgo.OpenBase()
	if err != nil {
		return
	}

	return sess.Exist(USER_COL_STR, bson.M{"email": email})
}

func AuthUser(name string, passWord string) (user *User, err error) {
	sess, err := mymgo.OpenBase()
	if err != nil {
		return
	}

	user = &User{}
	err = sess.WithC(USER_COL_STR, func(col *mgo.Collection) error {
		return col.Find(bson.M{"$or": []bson.M{bson.M{"email": name}, bson.M{"phoneNumb": name}}, "passWord": passWord}).One(user)
	})

	// 置空
	user.PhoneNumb = ""
	user.Email = ""
	user.Password = ""
	user.QQ = ""
	user.Age = ""
	user.Status = 0
	user.CreateTime = 0
	user.UpdateTime = 0
	user.DeleteTime = 0
	user.InvitationCode = ""
	user.Code = ""
	user.IsDeleted = false
	return
}
